package com.steam.pet.service.impl;

import com.steam.basic.service.impl.BaseServiceImpl;
import com.steam.pet.domain.PetType;
import com.steam.pet.mapper.PetTypeMapper;
import com.steam.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> petTypeTree() {
        //将所有的宠物类型装到map中，方便后续根据id查询
        List<PetType> types = petTypeMapper.loadAll();
        Map<Long, PetType> map = new HashMap<>();
        for (PetType type : types) {
            map.put(type.getId(),type);
        }

        //遍历所有的宠物类型，如果没有pid，直接添加到宠物类型树，有就找到自己的父类型，把自己添加到父类型的children中
        List<PetType> tree = new ArrayList<>();
        for (PetType type : types) {
            if(type.getPid()==null){
                tree.add(type);
            }else{
                Long pid = type.getPid();
                PetType parentType = map.get(pid);
                parentType.getChildren().add(type);
            }
        }

        return tree;
    }
}
